#!/bin/sh
### filename: dmenu_path

# Function to extract current PATH from the script
get_current_path() {
    grep '^export PATH=' "$0" | sed 's/export PATH=//'
}

# -------------------------- NEW: Help Argument Handler --------------------------
# Handle -h/--help: Show usage documentation
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    cat << EOF
Usage: $0 [OPTION] [ARGUMENT]

Description:
  A script to 1) manage a custom PATH (stored in the script itself) and 2) generate dmenu's program cache.
  Without arguments, it generates/uses dmenu's program cache (compatible with dmenu_run).

Options:
  -h, --help          Show this help message and exit
  -check              List the current custom PATH (one directory per line)
  -append <PATH>      Add a new directory to the end of the custom PATH (skips duplicates)
  -remove <PATH>      Remove a specific directory from the custom PATH (exact match required)

Examples:
  $0 -h                # Show this help
  $0 -check            # View current custom PATH
  $0 -append ~/bin     # Add "~/bin" to the custom PATH
  $0 -remove /usr/sbin # Remove "/usr/sbin" from the custom PATH
  $0                   # Generate dmenu's program cache (use with dmenu_run)

Notes:
  - The custom PATH is stored directly in this script (updated by -append/-remove).
  - Use absolute paths (e.g., /home/user/bin) for reliability with -append/-remove.
  - The dmenu cache is saved to: ${XDG_CACHE_HOME:-$HOME/.cache}/dmenu_run
EOF
    exit 0
fi
# -------------------------- END: Help Argument Handler --------------------------

# Handle -check flag: show current PATH
if [ "$1" = "-check" ]; then
    current_path=$(get_current_path)
    echo "Current script PATH:"
    echo "$current_path" | tr ':' '\n'  # Split into lines for readability
    exit 0
fi

# Handle -remove flag: delete a path from PATH
if [ "$1" = "-remove" ] && [ -n "$2" ]; then
    target_path="$2"
    current_path=$(get_current_path)
    script_path="$0"

    # Check if target exists in PATH
    if ! echo ":$current_path:" | grep -q ":$target_path:"; then
        echo "Path '$target_path' not found in PATH. No changes made."
        exit 0
    fi

    # Safely remove the target path (handles all cases)
    # Use awk to split PATH into elements, filter out target, then rejoin
    updated_path=$(echo "$current_path" | awk -v t="$target_path" '
        BEGIN {
            FS = ":";
            OFS = ":";
            first = 1;
        }
        {
            for (i=1; i<=NF; i++) {
                if ($i != t) {  # Keep only elements not equal to target
                    if (!first) printf OFS;
                    printf $i;
                    first = 0;
                }
            }
        }
    ')

    # Update the PATH line in the script
    sed -i "s|^export PATH=.*|export PATH=$updated_path|" "$script_path"
    echo "Removed '$target_path' from PATH. Updated PATH:"
    echo "$updated_path"
    exit 0
fi

# Handle -append flag: add new path
if [ "$1" = "-append" ] && [ -n "$2" ]; then
    new_path="$2"
    current_path=$(get_current_path)
    script_path="$0"

    # Check if new path is already in PATH (avoid duplicates)
    if ! echo ":$current_path:" | grep -q ":$new_path:"; then
        # If PATH is empty, don't add a leading colon
        [ -z "$current_path" ] && updated_path="$new_path" || updated_path="$current_path:$new_path"
        sed -i "s|^export PATH=.*|export PATH=$updated_path|" "$script_path"
        echo "Added '$new_path' to PATH. Updated PATH:"
        echo "$updated_path"
    else
        echo "Path '$new_path' is already in PATH. No changes made."
    fi
    exit 0
fi

# Original dmenu_run cache logic
cachedir="${XDG_CACHE_HOME:-"$HOME/.cache"}"
cache="$cachedir/dmenu_run"

[ ! -e "$cachedir" ] && mkdir -p "$cachedir"

# User-defined PATH (will be updated by -append/-remove)
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin

IFS=:
if stest -dqr -n "$cache" $PATH; then
    stest -flx $PATH | sort -u | tee "$cache"
else
    cat "$cache"
fi
